package collectionsx


/*-*- coding:utf-8 -*-
* @Author  : ygree 
* @Time    : 2021/7/4 4:21
* @Software : IntelliJ IDEA
*/

class Mapx {
    fun method() {
        /**to看上去像关键字，但事实上，它是个省略了点号和参数的特殊函数，to函数将它左边和右边的值转化成一对 Pair。
         */
//        val mapOf = mapOf(Pair("as", 78))

        val map = mapOf("a" to 1, "b" to 2, "c" to 3)

        /**[]取值运算符，读取键对应的值，如果键不存在就返回nullI
        getValue，读取键对应的值，如果键不存在就抛出异常
        getOrElse，读取键对应的值，或者使用匿名函数返回默认值
        getOrDefault，读取键对应的值，或者返回默认值
         */
        var withDefault = fun(key: String): Int {
            return key.length
        }
        println("map[k]            ${map["d"] ?: -1}")
        println("map.isEmpty       ${map.isEmpty()}")
        println("map.contains      ${map.contains("a")}")
        println("map.iterator      ${map.iterator()}")
        println("map.containsKey   ${map.containsKey("a")}")
        println("map.containsValue ${map.containsValue(1)}")
        println("map.getValue      ${map.getValue("a")}")
        println("map.getOrElse     ${map.getOrElse("a", { 100 })}")
        println("map.getOrDefault  ${map.getOrDefault("a", 100)}")
        println("map.withDefault   ${map.withDefault(withDefault)}")

    }

    fun forR() {
        val map = mapOf("ks" to 12, "as" to 12, "sas" to 34)
        for (entry in map) {

        }
        map.forEach() {
            println(it)
        }
        map.entries.forEach { }
        map.keys.forEach { }
        map.values.forEach { }
        map.filter { predicate -> true }
        map.filterNot { predicate -> true }
        map.filterKeys { predicate -> true }
        map.filterValues { predicate -> true }
//        map.filterTo() { predicate -> true }
        map.filterNot() { predicate -> true }

        map.maxOfOrNull { (key, value) -> value }
    }

    fun mutable() {
//        可变map
        println("====mutable=====")
        val mapOf = mapOf("a" to 1, "b" to 2, "c" to 3)

        println("old mapOf.plus    ${mapOf.plus("a" to 2)}")
        println("old mapOf         ${mapOf}")

        val mutable = mutableMapOf("a" to 1, "b" to 2, "c" to 3)
        println("old mutable       ${mutable}")
        println("new mutable.plus  ${mutable.plus("d" to 10)}")
        println("old mutable       ${mutable}")
        mutable.put("d", 4)
        mutable.remove("a")
        println("old mutable       ${mutable}")
    }
}

private  fun main() {
    Mapx().method()
    Mapx().mutable()
}